from django.shortcuts import render, HttpResponse, redirect
from user_mng import models
from task_market.models import Task, TaskApplication, Taskdata
from user_mng.models import users
from django.core import serializers
import json
from django.contrib import messages

'''from loguru import logger'''


# Create your views here.
def login(request):
    if not request.session.get('account'):
        staue = 'login'
    else:
        staue = 'logout'
    user_lists = {i.user_account: i.user_name for i in models.users.objects.all()}
    if request.session.get("account"):
        name = user_lists[request.session.get('account')]
        return redirect('task_market:user_mng:self')
    else:
        name = '请登录'
    if request.method == "GET":
        return render(request, "user_mng/login.html", {'name': name, 'staues': staue})

    user_list = {i.user_account: [i.user_pwd, i.user_type] for i in models.users.objects.all()}
    useraccount = request.POST.get("account")
    password = request.POST.get("pwd")
    if useraccount in user_list.keys() and password == user_list[useraccount][0]:
        request.session.clear()
        request.session["account"] = useraccount
        return redirect("task_market:index")
    # return HttpResponse("登录失败")
    return render(request, 'user_mng/login.html',
                  {"error_msg": "用户名或密码错误,请重试", 'name': name, 'staues': staue})


def signup(request):
    if not request.session.get('account'):
        staue = 'login'
    else:
        staue = 'logout'

    user_list = [i.user_account for i in models.users.objects.all()]
    useraccount = request.POST.get("account")
    username = request.POST.get("name")
    usertype = request.POST.get("type")
    password = request.POST.get("pwd")
    if not request.session.get("account"):
        name = '请登录'
    else:
        name = username
    if request.method == "GET":
        return render(request, "user_mng/signup.html", {'staues': staue, 'name': name})
    if useraccount in user_list:
        return render(request, 'user_mng/signup.html',
                      {"error_msg": "账户已存在，请登录", 'staues': staue, 'name': username})
    if len(password) < 4:
        return render(request, 'user_mng/signup.html',
                      {"error_msg": "密码过短，请重新设置", 'staues': staue, 'name': username})
    models.users.objects.create(user_account=useraccount, user_name=username, user_pwd=password, user_type=usertype)
    return redirect("task_market:user_mng:login")


def home(request):
    user_list = {i.user_account: i.user_type for i in models.users.objects.all()}
    if request.method == "GET":
        if not request.session.get("account"):
            return render(request, "user_mng/home.html", {'name': "请登录"})
        else:
            return render(request, "user_mng/home.html", {'name': user_list[request.session.get('account')]})


# 管理员界面
def admin(request):
    return redirect('task_market:user_mng:signup')


def self(request):
    if not request.session.get('account'):
        staue = 'login'
    else:
        staue = 'logout'

    if not request.session.get("account"):
        return redirect("task_market:user_mng:login")
    # 获得身份
    user_list = {i.user_account: [i.user_name, i.user_id, i.user_money, i.user_score] for i in models.users.objects.all()}
    user_score = user_list[request.session.get('account')][3]
    user_money = user_list[request.session.get('account')][2]
    user_id = user_list[request.session.get('account')][1]
    user_type = users.objects.get(user_id=user_id).user_type
    print('user_type', user_type)
    print('type', type(user_type))
    all_task = Task.objects.all().order_by('task_publish_time')
    Id = []
    if user_type == 0:  # 管理员
        pass
    elif user_type == 1:  # 标注者
        apply_task_id = TaskApplication.objects.filter(
            Task_applier_id=user_list[request.session.get('account')][1]).values('Task_id')
        for iid in apply_task_id:
            Id.append(iid['Task_id'])

    elif user_type == 2:  # 发布者

        publish_task_id = Task.objects.filter(
            task_publish_id=user_id).values('id')
        print('###########', publish_task_id)
        for iid in publish_task_id:
            Id.append(str(iid['id']))
        print('###########', Id)
    if request.method == 'POST':
        user = users.objects.get(user_id=user_id)
        user.user_money+= float(request.POST.get('user_money') or 0)
        user.save()
        return render(request, "user_mng/self.html",
                      {'user_type': user_type, 'name': user_list[request.session.get('account')][0], 'staues': staue,
                       'apply_task_id': Id, 'all_task': all_task, 'money': user.user_money, 'score': user_score})
    # 标注者查看自己进行中任务
    # qs = TaskApplication.objects.filter(Task_applier_id=user_list[request.session.get('account')][1]).order_by("-Apply_time")
    # print(type(Id[0]))
    item = request.GET.get('search')
    if not item:
        return render(request, "user_mng/self.html",
                      {'user_type': user_type, 'name': user_list[request.session.get('account')][0], 'staues': staue,
                       'apply_task_id': Id, 'all_task': all_task, 'money': user_money, 'score': user_score})
    else:
        task_list = Task.objects.filter(task_name__icontains=item)
        return render(request, 'task_market/all_grid.html',
                      {'tasks': task_list, 'name': user_list[request.session.get('account')][0], 'staues': staue})


def self_caiwu(request):
    if not request.session.get('account'):
        staue = 'login'
    else:
        staue = 'logout'
    user_list = {i.user_account: i.user_name for i in models.users.objects.all()}
    if not request.session.get("account"):
        return redirect('task_market:user_mng:login')
    if request.method == "GET":
        return render(request, "user_mng/self_caiwu.html",
                      {'name': user_list[request.session.get('account')], 'staues': staue})


def log(request):
    if not request.session.get('account'):
        '''user_list = {i.user_account: [i.user_pwd, i.user_type] for i in models.users.objects.all()}
        useraccount = request.POST.get("account")
        password = request.POST.get("pwd")
        if useraccount in user_list.keys() and password == user_list[useraccount][0]:
            request.session.clear()
            request.session["account"] = useraccount
            if user_list[useraccount][1] == 0:
                return redirect("http://127.0.0.1:8000/admin")
            else:
                return redirect("http://127.0.0.1:8000/home")
        # return HttpResponse("登录失败")
        return render(request, 'user_mng/login.html', {"error_msg": "用户名或密码错误,请重试"})'''
        return redirect('task_market:user_mng:login')
    else:
        request.session.flush()
        return redirect('task_market:index')


def download_annotations(request, task_id):
    # 查询要导出的数据
    data = Taskdata.objects.filter(taskdata_task_id=task_id).values('taskdata_id', 'taskdata_content',
                                                                    'taskdata_result')

    # 将数据转换为字典列表
    data_list = list(data)

    # 构建JSON格式的数据
    serialized_data = json.dumps(data_list)

    file_name = '{}_data.json'.format(task_id)  # 使用任务ID构建文件名

    # 创建JSON文件的响应
    response = HttpResponse(content_type='application/json')
    response['Content-Disposition'] = 'attachment; filename="{}"'.format(file_name)

    # 将序列化的数据写入响应
    response.write(serialized_data)

    return response


def task_end(request, task_id):
    task = Task.objects.get(id=task_id)
    task.task_status = 4
    task.save()
    return redirect("task_market:user_mng:self")
